import { consts } from "@/module-00-codebase/pkg-00-const";
import { Bi } from "@/module-00-codebase/pkg-01-container";
import { asyncOne, Throwable } from "@/module-00-codebase/pkg-02-tool";
import { User } from "@/module-00-codebase/pkg-08-entity/user";

export class UserManagerImpl {
  public async getUser() {
    /**/ if (tokenKeeping()) return user;
    else if (tokenMissing()) return (user = token = null);
    else {
      return await asyncOne(async () => {
        try {
          const user_res = await Bi.rpc.send({ action: "getone", resourceName: "innerUser" });
          token = Bi.cacheManager.read("token");
          user = user_res?.data?.data || null;
          if (!token || !user) Throwable("Sign in failed.");
        } catch ( ex:unknown ) {
 const e = ex instanceof Error?ex:new Error(JSON.stringify(ex));
          token = user = null;
          Bi.loading.on(e.message, consts.error_loading_ms);
        }
        return user;
      }, LOCK_SYMBOL);
    }
  }
}
let token: string | null = null;
let user: User | null = null;
const tokenKeeping = () => token === Bi.cacheManager.read("token");
const tokenMissing = () => !Bi.cacheManager.read("token");
const LOCK_SYMBOL = Symbol();
